/*
* 新人专区批量添加商品
* @Author: Li Yujie
* @Date: 2020-11-23
*/
<template>
    <div class="wrapper">
        <div class="page">
            <!-- header -->
            <div class="header">
                <div class="header-title">
                    批量添加商品
                </div>
            </div>
            <!-- /header -->
            <!-- table -->
            <el-form
                :model="ruleForm"
                :rules="rules"
                style="height: calc(100% -  100px)"
                ref="ruleForm"
            >
                <el-table
                    :data="ruleForm.tableData"
                    height="100%"
                    style="width: 100%;"
                    ref="tempLateName"
                    class="data-table"
                    @select-all="handleSelectAll"
                >
                    <el-table-column
                        align="center"
                        type="selection"
                        width="80"
                    >
                        <template slot-scope="scope">
                            <div
                                v-for="item in scope.row.product_list"
                                :key="item.product_no"
                                class="table-item"
                            >
                                <el-checkbox
                                    v-model="item.check_status"
                                    :true-label="1"
                                    :false-label="0"
                                />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="商品缩略图"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <img
                                :src="scope.row.goods_cover"
                                style="width: 60px"
                                @click="fnShowPreview(scope.row.goods_cover)"
                            >
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="goods_no"
                        label="商品编号"
                        show-overflow-tooltip
                        align="left"
                    />
                    <el-table-column
                        prop="goods_title"
                        label="原商品标题"
                        show-overflow-tooltip
                        align="left"
                    />
                    <el-table-column
                        label="商品标题"
                        show-overflow-tooltip
                        align="center"
                        width="130"
                    >
                        <template slot-scope="scope">
                            <div class="table-item">
                                <el-form-item
                                    :prop="`tableData.${scope.$index}.welfare_title`"
                                    :rules="rules.welfare_title"
                                >
                                    <el-input
                                        v-model="scope.row.welfare_title"
                                        clearable
                                        size="small"
                                    />
                                </el-form-item>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="佣金比例"
                        show-overflow-tooltip
                        align="center"
                        width="130"
                    >
                        <template slot-scope="scope">
                            <div class="table-item">
                                <el-form-item
                                    :prop="`tableData.${scope.$index}.commission_rate`"
                                    :rules="rules.commission_rate"
                                >
                                    <el-input
                                        v-model="scope.row.commission_rate"
                                        size="small"
                                    >
                                        <span slot="suffix">%</span>
                                    </el-input>
                                </el-form-item>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="商品规格"
                        align="center"
                        width="300"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="(item, index) in scope.row.product_list"
                                :key="item.product_no"
                                :style="`color:${item.check_status ? '#1890FF' : ''};cursor: pointer`"
                                @click="handleChecked(scope.row, scope.$index, index)"
                            >
                                <span
                                    v-for="(option,i) in item.spec_list"
                                    :key="i"
                                    style="margin: 0 6px"
                                >
                                    {{ `${option.spec_name} : ${option.spec_value}` }}
                                </span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="原售价"
                        show-overflow-tooltip
                        align="center"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="item in scope.row.product_list"
                                :key="item.product_no"
                            >
                                ￥{{ item.product_price }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="新人价"
                        align="center"
                        width="130"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="(item,index) in scope.row.product_list"
                                :key="item.product_no"
                            >
                                <el-form-item
                                    :prop="`tableData.${scope.$index}.product_list[${index}]`"
                                    :rules="rules.welfare_price"
                                >
                                    <el-input
                                        v-model="item.welfare_price"
                                        clearable
                                        size="small"
                                        :disabled="!scope.row.product_list[index].check_status"
                                        @blur="calcPlatformMoney(item)"
                                        @click.native="clickDisableInput(scope.row, scope.$index, index)"
                                    />
                                </el-form-item>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="活动库存"
                        align="center"
                        width="270"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="(item,index) in scope.row.product_list"
                                :key="item.product_no"
                            >
                                <div style="display: flex; align-items: center;justify-content: center">
                                    <el-select
                                        v-model="item.stock_type"
                                        style="width: 126px;margin-bottom: 22px"
                                        size="small"
                                        :disabled="!scope.row.product_list[index].check_status"
                                        @change="handleStockTypeChange($event, scope.$index, index)"
                                        @click.native="clickDisableInput(scope.row, scope.$index, index)"
                                    >
                                        <el-option
                                            label="同步商家库存"
                                            :value="1"
                                        />
                                        <el-option
                                            label="自定义"
                                            :value="2"
                                        />
                                    </el-select>
                                    <el-form-item
                                        :prop="`tableData.${scope.$index}.product_list[${index}]`"
                                        :rules="rules.welfare_stock"
                                        v-if="item.stock_type === 2"
                                    >
                                        <el-input
                                            oninput="value = value.replace(/[^\d]/g,'')"
                                            placeholder="活动库存"
                                            v-model.number="item.welfare_stock"
                                            style="width: 84px;"
                                            size="small"
                                            :disabled="!scope.row.product_list[index].check_status"
                                            @click.native="clickDisableInput(scope.row, scope.$index, index)"
                                        />
                                    </el-form-item>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="商家设置库存"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="item in scope.row.product_list"
                                :key="item.product_no"
                            >
                                {{ item.product_stock }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="是否平台补贴"
                        align="center"
                        width="110"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="(item, index) in scope.row.product_list"
                                :key="item.product_no"
                            >
                                <div
                                    style="display: flex; align-items: center;justify-content: center"
                                >
                                    <el-form-item style="margin-top: -4px">
                                        <el-select
                                            v-model="item.shop_subsidy_enable"
                                            size="small"
                                            style="width: 100px"
                                            @change="calcPlatformMoney(item, 'clear')"
                                            :disabled="!scope.row.product_list[index].check_status"
                                            @click.native="clickDisableInput(scope.row, scope.$index, index)"
                                        >
                                            <el-option
                                                label="平台补贴"
                                                :value="1"
                                            />
                                            <el-option
                                                label="商家全部补贴"
                                                :value="0"
                                            />
                                            <el-option
                                                label="商家部分补贴"
                                                :value="2"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="商家补贴金额"
                        align="center"
                        width="130"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="(item,index) in scope.row.product_list"
                                :key="item.product_no"
                            >
                                <div
                                    style="display: flex; align-items: center;justify-content: center"
                                >
                                    <el-form-item
                                        :prop="`tableData.${scope.$index}.product_list[${index}]`"
                                        :rules="rules.shop_subsidy_money_by_shop"
                                        style="margin-top: -4px"
                                    >
                                        <el-input
                                            v-model="item.shop_subsidy_money_by_shop"
                                            placeholder="商家补贴金额"
                                            size="small"
                                            clearable
                                            style="width: 120px"
                                            :disabled="!scope.row.product_list[index].check_status || item.shop_subsidy_enable !== 2"
                                            @blur="calcPlatformMoney(item)"
                                            @click.native="clickDisableInput(scope.row, scope.$index, index)"
                                        />
                                    </el-form-item>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="平台补贴金额"
                        align="center"
                        width="130"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="(item) in scope.row.product_list"
                                :key="item.product_no"
                            >
                                <div style="display: flex; align-items: center;justify-content: center">
                                    <el-form-item>
                                        {{ item.shop_subsidy_money_by_platform }}
                                    </el-form-item>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="排序号"
                        align="center"
                        width="130"
                    >
                        <template slot-scope="scope">
                            <div class="table-item">
                                <el-form-item
                                    :prop="`tableData.${scope.$index}.welfare_sort`"
                                    :rules="rules.welfare_sort"
                                >
                                    <el-input
                                        oninput="value = value.replace(/[^\d]/g,'')"
                                        v-model.number="scope.row.welfare_sort"
                                        clearable
                                        size="small"
                                    />
                                </el-form-item>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="活动状态设置"
                        align="center"
                        width="200px"
                    >
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.welfare_status"
                                active-text="上架"
                                inactive-text="下架"
                                :active-value="1"
                                :inactive-value="0"
                            />
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <!-- /table -->
            <div class="btn-group">
                <el-button
                    size="medium"
                    style="width: 120px"
                    @click="handleCancel()"
                >
                    取消
                </el-button>
                <el-button
                    size="medium"
                    type="primary"
                    style="width: 120px"
                    @click="handleSubmit()"
                >
                    完成
                </el-button>
            </div>
        </div>

        <!-- 图片预览 -->
        <img-preview ref="preview"/>

        <!-- 预算提示弹窗 -->
        <show-dialog
            ref="showDialog"
            :dialog="showDialog"
            :width="360"
            :cancel-text="'取消'"
            :confirm-text="'确定'"
            :title="'温馨提示'"
            :content="`当前新人专区的平台补贴支出在计划时间${ '2021/5/24-2021/6/24' }已无预算，暂无法添加新人专区商品`"
            @close="showDialog = false"
            @emit="() => {
                this.$router.push({
                    path: '/student/new-people-list'
                });
            }"
        />
    </div>
</template>

<script>
import showDialog from '@/components/common/dialog.vue';
import {back} from '@/mixin/back';
import imgPreview from '@/components/common/img-preview';
const numberReg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/;

export default {
    name: "GoodsEditBatch",
    data() {
        const validatePrice = (rule, value, callback) => {

            if(value.check_status && !value.welfare_price) {
                callback(new Error('请输入新人价'));
            } else if(value.welfare_price && !numberReg.test(value.welfare_price)) {
                callback(new Error('新人价为数字'));
            } else {
                callback();
            }
        };
        const validateStock = (rule, value, callback) => {

            if(value.check_status && !value.welfare_stock && value.welfare_stock !== 0) {
                callback(new Error('请输入活动库存'));
            } else {
                callback();
            }
        };
        const validateSubsidy = (rule, value, callback) => {
            if (value.check_status && value.shop_subsidy_money_by_shop === '') {
                callback(new Error('请填写补贴金额'));
            } else if (value.shop_subsidy_money_by_shop && !numberReg.test(value.shop_subsidy_money_by_shop)) {
                callback(new Error('金额必须未数字'));
            } else {
                callback();
            }
        };

        return {
            ruleForm: {
                tableData: [],
            },
            rules: {
                welfare_title: [
                    { required: true, message: '请输入商品标题', trigger: 'blur' }
                ],
                commission_rate: [
                    { required: true, message: '佣金比例不能为空', trigger: 'blur' },
                    { pattern: numberReg, message: '佣金比例必须为数字', trigger: 'blur' }
                ],
                welfare_price: [
                    { validator: validatePrice, trigger: 'blur' },
                ],
                welfare_stock: [
                    { validator: validateStock, trigger: 'blur' },
                ],
                welfare_sort: [
                    { required: true, message: '请输入排序号', trigger: 'blur' }
                ],
                shop_subsidy_money_by_shop: [
                    {validator: validateSubsidy, trigger: 'blur'}
                ],
            },
            showDialog: false
        };
    },
    mixins: [back],
    components: {
        imgPreview,
        showDialog
    },
    mounted() {
        this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '商城'}, {title: '新人专区', path: '/student/new-people-list'}, {title: '批量添加商品'}]);
        this.init();
    },

    methods: {

        init() {
            let goodsList = JSON.parse(this.$route.query.goodsList);

            goodsList.map(item => {
                item.welfare_title = item.goods_title;
                item.welfare_sort = 99;
                item.commission_rate = item.goods_commission_rate;
                item.product_list.map(subItem => {
                    subItem.welfare_price = '';
                    subItem.check_status = 0;
                    this.$set(subItem, 'stock_type', 1);
                    this.$set(subItem, 'welfare_stock', -1);
                    this.$set(subItem, 'shop_subsidy_enable', 1);
                    this.$set(subItem, 'shop_subsidy_money_by_shop', 0);
                    this.calcPlatformMoney(subItem);
                });
            });
            this.ruleForm.tableData = goodsList;
        },
        /**
         * 查看图片
         * @param   {String}    images      //单图预览
         * @param   {Array}     images      //多图预览
         */
        fnShowPreview(images) {
            if (images && Object.prototype.toString.call(images) == '[object String]') {
                this.$refs.preview.show([
                    images
                ]);
            } else if (images && Object.prototype.toString.call(images) == '[object Array]') {
                this.$refs.preview.show(images);
            } else {
                this.$message({
                    type: 'warning',
                    message: '图片类型错误'
                });
            }
        },
        /**
         * 取消返回列表
         */
        handleCancel() {
            this.$confirm('返回后将不会保存您所修改的内容,是否返回?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$router.push({
                    path: '/student/new-people-list'
                });
            });
        },

        /**
         * 提交数据
         */
        handleSubmit() {

            this.$refs.ruleForm.validate((valid) => {
                if(valid) {
                    console.log(this.ruleForm.tableData);

                    let tableData = [...this.ruleForm.tableData];
                    let params = {
                        welfare_json: JSON.stringify(tableData)
                    };

                    this.$post('/student/shop_welfare%5Cadd_batch', params, resp => {
                        if (resp.code === 1) {
                            if(resp.data.result === 1) {
                                this.$notify({
                                    title: '提示',
                                    message: '保存成功',
                                    type: 'success',
                                    duration: 2000
                                });
                                setTimeout(() => {
                                    this.$router.push({
                                        path: '/student/new-people-list'
                                    });
                                }, 500);
                            } else {
                                this.$zdConfirm(`当前新人专区的平台补贴支出${resp.data.result === -1 ? '不在财控计划时间内' : '在计划时间已无预算'} ，暂无法添加新人专区商品，如需要增加预算，请联系平台财务人员。`, '温馨提示', {
                                    confirmButtonText: '知道了',
                                    hasCancelButton: false,
                                    type: 'warning'
                                }).then(() => {});
                            }
                        } else {
                            this.$notify({
                                title: '提示',
                                message: resp.msg,
                                duration: 2000,
                                type: 'warning'
                            });
                        }
                    });
                }
            });
        },

        /**
         * 点击规格选中当前规格
         * @param row
         * @param rowIndex
         * @param index
         */
        handleChecked(row, rowIndex, index) {

            if(row.product_list[index].check_status) {
                row.product_list[index].check_status = 0;
            } else {
                row.product_list[index].check_status = 1;
            }
        },

        /**
         * 点击禁用的input
         * @param row
         * @param rowIndex
         * @param index
         */
        clickDisableInput(row, rowIndex, index) {
            if(!row.product_list[index].check_status) {
                this.$message.warning('请勾选该规格');
            }
        },

        /**
         * 点击全选
         * @param val
         */
        handleSelectAll(val) {
            this.ruleForm.tableData.map(item => {
                item.product_list.map(subItem => {
                    if(val.length) {
                        subItem.check_status = 1;
                    } else {
                        subItem.check_status = 0;
                    }
                });
            });
        },

        /**
         * 选择库存类型
         * @param val
         * @param tableIndex
         * @param skuIndex
         */
        handleStockTypeChange(val, tableIndex, skuIndex) {
            if(val === 1) {
                this.ruleForm.tableData[tableIndex].product_list[skuIndex].welfare_stock = -1;
            } else {
                this.ruleForm.tableData[tableIndex].product_list[skuIndex].welfare_stock = 0;
            }
        },

        /**
         * 计算平台与商家补贴金额
         * @param row
         * @param type
         */
        calcPlatformMoney(row, type) {
            let product_price = Number(row.product_price);
            let welfare_price = Number(row.welfare_price);
            let subsidy_money_all = (product_price - welfare_price).toFixed(2);

            // 平台全部补贴
            if(row.shop_subsidy_enable === 1) {
                this.$set(row, 'shop_subsidy_money_by_shop', 0);
                this.$set(row, 'shop_subsidy_money_by_platform', subsidy_money_all);
            }
            // 商家全部补贴
            if(row.shop_subsidy_enable === 0) {
                this.$set(row, 'shop_subsidy_money_by_shop', subsidy_money_all);
                this.$set(row, 'shop_subsidy_money_by_platform', 0);
            }
            // 商家部分补贴
            if(row.shop_subsidy_enable === 2) {
                if(type) {
                    this.$set(row, 'shop_subsidy_money_by_shop', '');
                }
                let shop_subsidy_money_by_platform = subsidy_money_all - Number(row.shop_subsidy_money_by_shop);

                this.$set(row, 'shop_subsidy_money_by_platform', shop_subsidy_money_by_platform < 0 ? '0.00' : shop_subsidy_money_by_platform.toFixed(2));
            }
        }
    }
};
</script>

<style scoped lang="less">

.wrapper {
    width: 100%;
    position: relative;
    background: #fff;
    box-sizing: border-box;

    .data-table {
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
    }
    .page {
        width: 100%;
        height: calc(100% - 60px);
        background: #fff;
        display: flex;
        flex-direction: column;
        /*header*/

        .header {
            height: 68px;
            padding: 24px;
            box-sizing: border-box;
            box-shadow: 0px -1px 0px 0px #F0F2F5;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #F0F2F5;

            .header-title {
                color: #333333;
                font-size: 20px;
                height: 20px;
                font-weight: 500;
                position: relative;
                margin: 24px 0 24px 12px;

                &::before {
                    content: '';
                    position: absolute;
                    left: -8px;
                    top: -1px;
                    width: 3px;
                    height: 20px;
                    background: #1890FF;
                }
            }
        }

        .btn-group {
            text-align: center;
            margin-top: 24px;
            .el-button {
                margin: 0 24px;
            }
        }

        .table-item {
            margin: 28px 0;
            height: 30px;
        }
    }
}
</style>
